<?php

// phpMyRealty 3
//
// File Name: editlistings.php
// File Location : ./admin/
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com

// Include configuration file and general functions
define('PMR', 'true');
define('PMRADMIN', 'true');

include ( '.././config.php' );
include ( PATH . '/defaults.php' );

// ----------------------------------------------------------------------
// ADMIN SECTION / EDIT SELECTED LISTING

// Title tag content
$title = $lang['Menu_Submit_Property'];

$initAjax = TRUE;

if (isset($initAjax) && $initAjax)
 include ( PATH . '/includes/ajaxDropdowns.php');

// Template header
include ( PATH . '/admin/template/header.php' );

// If logged we can start the page output
if (adminAuth($session->fetch('adminlogin'), $session->fetch('adminpassword')))

 {
  // Include navigation panel
  include ( PATH . '/admin/navigation.php' );

  // Make sure this administrator can access this script
  adminPermissionsCheck('manage_listings', $session->fetch('adminlogin')) or error ('Critical Error', 'Incorrect privileges');

  // Check the id variable passed to the script
  if (isset($_GET['id']) && eregi('^[0-9]+$', $_GET['id']))

   {

    // Fetching the listing data
    $sql = 'SELECT * FROM ' . PROPERTIES_TABLE . ' WHERE id = ' . intval($_GET['id']) . ' LIMIT 1';
    $r = $db->query( $sql );
    $f = $db->fetcharray( $r );

    $approved_date = $f['date_approved'];

    // If the property main photo was uploaded we start this routine
    if (isset($_POST['submit_image'])
    && $_POST['submit_image'] == $lang['Listing_Submit_Image'])
     {

      // We think that the image is uploaded or will
      // return FALSE if the upload_image function
      // will fail
      $uploaded = TRUE;

      // Upload and resize the image
      upload_image ( 'images', $f['id'], $_FILES['image_file']['tmp_name'], $conf['image_resampled_width'] ) or $uploaded = FALSE;

     }

    // If user removed the image we run the following
    if (isset($_POST['submit_image_remove'])
    && $_POST['submit_image_remove'] == $lang['Listing_Submit_Image_Remove'])
     remove_image ( 'images' , $f['id']);

    if (isset($_POST['submit_video2'])
    && $_POST['submit_video2'] == $lang['Video_Remove']) {
     unlink (PATH . '/video/' . $f['id'] . '.flv');
    }

	// If uploading a video
    if (isset($_POST['submit_video'])
    && $_POST['submit_video'] == $lang['Video_Upload'])
     {

		// If MEncoder is enabled, convert it
		if ($conf['mencoder'] == 'ON')
		{

	      $raw_video_path = $_FILES['video_file']['tmp_name'];
	      $new_flv = PATH . '/video/' . $f['id'] . '.flv';

	      $mencoder_cmd = $conf['path_to_mencoder'] . ' ' . $raw_video_path . ' -o ' . $new_flv . ' -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=800:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -vf scale=450:400 -srate 22050';
	      @exec($mencoder_cmd . ' 2>&1', $output);

	      if (!file_exists($new_flv)) {
	      $mencoder_cmd = $conf['path_to_mencoder'] . ' ' . $raw_video_path . ' -o ' . $new_flv . ' -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=800:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -vop scale=450:400 -srate 22050';
	      @exec($mencoder_cmd . ' 2>&1', $output);
	      }

	      if (!file_exists($new_flv)) {
	      $mencoder_cmd = $conf['path_to_mencoder'] . ' ' . $raw_video_path . ' -o ' . $new_flv . ' -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=800:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -vf scale=450:400 -srate 22050';
	      @exec($mencoder_cmd . ' 2>&1', $output);
	      }

				if ( file_exists( $raw_video_path ) )
				{
		      		@unlink($raw_video_path);
				}

			if (file_exists(PATH . '/video/' . $f['id'] . '.flv'))
				$video_uploaded = TRUE;
			else
				$video_uploaded = FALSE;

		}
		else
		{

			// Make sure this is an FLV, if so copy it
			$ext = end(explode('.', $_FILES['video_file']['name']));

			if ($ext == 'flv')
			{
				if (copy($_FILES['video_file']['tmp_name'], PATH . '/video/' . $f['id'] . '.flv'))
					$video_uploaded	= TRUE;
				else
					$video_uploaded	= FALSE;
			}

		}

     }

    // If the property banner was uploaded we start this routine
    if (isset($_POST['submit_banner'])
    && $_POST['submit_banner'] == $lang['Listing_Submit_Banner'])
     {

      // We think that the image is uploaded or will
      // return FALSE if the banner_upload function
      // will fail
      $uploaded_banner = TRUE;

      // Upload the banner
      banner_upload ( 'banners', $f['id'], $_FILES['image_file']['tmp_name'], $conf['banner_width'], $conf['banner_height'], $conf['banner_size'] ) or $uploaded_banner = FALSE;

     }

    // If user removed the banner we run the following
    if (isset($_POST['submit_banner_remove'])
    && $_POST['submit_banner_remove'] == $lang['Listing_Submit_Banner_Remove'])
     banner_remove ( 'banners' , $f['id']);

    // If the Submit button was pressed we start this routine
    if (isset($_POST['submit_listing'])
    && $_POST['submit_listing'] == $lang['Listing_Submit'])
     {

      $form = array();

      // Change checkbox arrays into a string, with ':' as a separator
      if (isset($_POST['buildings']) && is_array($_POST['buildings'])) $_POST['buildings'] = implode (':', $_POST['buildings']); else $_POST['buildings'] = '';
      if (isset($_POST['appliances']) && is_array($_POST['appliances'])) $_POST['appliances'] = implode (':', $_POST['appliances']); else $_POST['appliances'] = '';
      if (isset($_POST['features']) && is_array($_POST['features'])) $_POST['features'] = implode (':', $_POST['features']); else $_POST['features'] = '';

      if (empty($_POST['display_address'])) $_POST['display_address'] = 'NO';

      // safehtml() all the POST variables
      // to insert into the database or
      // print the form again if errors
      // found

      $form = array_map('safehtml', $_POST);
      // Cut the description size to the one set in the configuration
      // just in case the java Script is disabled in user browser
      $form['description'] = substr ($form['description'], 0, $conf['listing_description_size']);

      echo table_header ( $lang['Information'] );

      // Initially we think that no errors were found
      $count_error = 0;

      if (
       (isset($form['location1']) && $form['location1'] == 'ANY') ||
       (isset($form['location2']) && $form['location2'] == 'ANY') ||
       (isset($form['location3']) && $form['location3'] == 'ANY')
      ) {
       echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Location'] . '</span><br />'; $count_error++;
      }

      // Check for the empty or incorrect required fields
      if (empty($form['title']) || strlen($form['title']) < 4 )
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Title'] . '</span><br />'; $count_error++;}

      if ((!empty($form['bathrooms'])) && !eregi('^[0-9]+$', $form['bathrooms']))
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Bathrooms'] . '</span><br />'; $count_error++;}

      if ((!empty($form['half_bathrooms'])) && !eregi('^[0-9]+$', $form['half_bathrooms']))
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Half_Bathrooms'] . '</span><br />'; $count_error++;}

      if ((!empty($form['bedrooms'])) && !eregi('^[0-9]+$', $form['bedrooms']))
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Bedrooms'] . '</span><br />'; $count_error++;}

      if ((!empty($form['year_built'])) && !eregi('^[0-9]+$', $form['year_built']))
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Year_Built'] . '</span><br />'; $count_error++;}

      if ((!empty($form['price'])) && !eregi('^[0-9]+$', $form['price']))
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Price'] . '</span><br />'; $count_error++;}

      if ((!empty($form['status'])) && !eregi('^[0-9]+$', $form['status']))
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Listing_Status'] . '</span><br />'; $count_error++;}

      if ( (!empty($form['start_date']) && !empty($form['end_date']) && $form['start_date'] >= $form['end_date'])
      || (!empty($form['start_date']) && empty($form['end_date']) )
      || (empty($form['start_date']) && !empty($form['end_date']) ) )
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Featured_Dates'] . '</span><br />'; $count_error++;}

      // Check if this listing title already exists
      if (strcasecmp($conf['allow_same_title'], 'ON')) {
         $sql = 'SELECT title FROM ' . PROPERTIES_TABLE . ' WHERE title = "' . $form['title'] . '" AND id <> "' . intval($_GET['id']) . '"';
         $r = $db->query($sql) or error ('Critical Error', mysql_error () );

         if ($db->fetcharray($r) > 0 )
          { echo $lang['Title_Used'] . '<br />'; $count_error++;}
      }

      //

      if ($count_error > '0')
       echo '<br /><span class="warning">' . $lang['Errors_Found'] . ': ' . $count_error . '</span><br />';

      // If no errors were found during the above checks we continue
      if ($count_error == '0')
       {
        // Update user details in the database

        // Get the user IP address
        $user_ip = $_SERVER['REMOTE_ADDR'];
        // If there is more than one IP
        // get the first one from the
        // comma separated list
        if ( strstr($user_ip, ', ') )
         {
          $ips = explode(', ', $user_ip);
          $user_ip = $ips[0];
         }

        if (!isset($form['location1'])) $form['location1'] = '0';
        if (!isset($form['location2'])) $form['location2'] = '0';
        if (!isset($form['location3'])) $form['location3'] = '0';

        if ($form['approved'] != 1) {
            // If listing is not approved anymore, reset the approval date
            $approved_date = 'NULL';
        } elseif ($approved_date && strncmp($approved_date, '0000-00-00', 10)) {
            // If already approved, don't change the date
            $approved_date = '"'.$approved_date.'"';
        } else {
            // Newly approved
            $approved_date = 'NOW()';
        }
        
       // Add custom value if text input field
       $custom_fields = array(
       					'custom1' => $form['custom1'],
       					'custom2' => $form['custom2'],
       					'custom3' => $form['custom3'],
       					'custom4' => $form['custom4'],
       					'custom5' => $form['custom5'],
       					'custom6' => $form['custom6'],
       					'custom7' => $form['custom7'],
       					'custom8' => $form['custom8'],
       					'custom9' => $form['custom9'],
       					'custom10' => $form['custom10'],
       );
       foreach ( $custom_fields AS $key => $value )
       {
       		if ( $value != '' )
       		{
       			// Check if this is an input field
       			$sql = "SELECT id, type FROM " . FIELDS_TABLE . " WHERE field = '" . $key . "' ";
       			$r = $db->query( $sql ) or error( 'Critical Error', mysql_error() );
       			$f = $db->fetcharray( $r );
       			if ( $f['type'] == 'input' )
       			{      				
       				// Override value of this custom input box with the primary key of the VALUES table
       				$form[$key] = '{INPUT}' . $value;
       			}
       		}
       }

        // Create a mysql query
        $sql =  'UPDATE '. PROPERTIES_TABLE . ' SET
             mls = "' . @$form['mls'] . '",
          	 type = "' . $form['type']. '",
	         style = "' . $form['style']. '",
			title = "' . $form['title'] . '", title2 = "' . $form['title2'] . '", title3 = "' . $form['title3'] . '", title4 = "' . $form['title4'] . '", title5 = "' . $form['title5'] . '",
			title6 = "' . $form['title6'] . '", title7 = "' . $form['title7'] . '", title8 = "' . $form['title8'] . '", title9 = "' . $form['title9'] . '", title10 = "' . $form['title10'] . '",
			title11 = "' . $form['title11'] . '", title12 = "' . $form['title12'] . '", title13 = "' . $form['title13'] . '", title14 = "' . $form['title14'] . '", title15 = "' . $form['title15'] . '",
			title16 = "' . $form['title16'] . '", title17 = "' . $form['title17'] . '", title18 = "' . $form['title18'] . '", title19 = "' . $form['title19'] . '", title20 = "' . $form['title20'] . '",
			title21 = "' . $form['title21'] . '", title22 = "' . $form['title22'] . '", title23 = "' . $form['title23'] . '", title24 = "' . $form['title24'] . '", title25 = "' . $form['title25'] . '",
			title26 = "' . $form['title26'] . '", title27 = "' . $form['title27'] . '", title28 = "' . $form['title28'] . '", title29 = "' . $form['title29'] . '", title30 = "' . $form['title30'] . '",
			description = "' . $form['description'] . '", description2 = "' . $form['description2'] . '", description3 = "' . $form['description3'] . '", description4 = "' . $form['description4'] . '", description5 = "' . $form['description5'] . '",
			description6 = "' . $form['description6'] . '", description7 = "' . $form['description7'] . '", description8 = "' . $form['description8'] . '", description9 = "' . $form['description9'] . '", description10 = "' . $form['description10'] . '",
			description11 = "' . $form['description11'] . '", description12 = "' . $form['description12'] . '", description13 = "' . $form['description13'] . '", description14 = "' . $form['description14'] . '", description15 = "' . $form['description15'] . '",
			description16 = "' . $form['description16'] . '", description17 = "' . $form['description17'] . '", description18 = "' . $form['description18'] . '", description19 = "' . $form['description19'] . '", description20 = "' . $form['description20'] . '",
			description21 = "' . $form['description21'] . '", description22 = "' . $form['description22'] . '", description23 = "' . $form['description23'] . '", description24 = "' . $form['description24'] . '", description25 = "' . $form['description25'] . '",
			description26 = "' . $form['description26'] . '", description27 = "' . $form['description27'] . '",	description28 = "' . $form['description28'] . '", description29 = "' . $form['description29'] . '",	description30 = "' . $form['description30'] . '",
	         size = "' . $form['size'] . '",
	         dimensions = "' . $form['dimensions'] . '",
	         bathrooms = "' . $form['bathrooms'] . '",
	         half_bathrooms = "' . $form['half_bathrooms'] . '",
	         bedrooms = "' . $form['bedrooms'] . '",
		     location2 = "' . $form['location1'] . '#' . $form['location2'] . '#' . $form['location3'] . '",
             zip = "' . @$form['zip'] . '",
	         address1 = "' . $form['address1'] . '",
	         address2 = "' . $form['address2'] . '",
	         display_address = "' . $form['display_address'] . '",
	         price = "' . $form['price'] . '",
	         directions = "' . $form['directions'] . '",
	         year_built = "' . $form['year_built'] . '",
	         buildings = "' . $form['buildings'] . '",
	         appliances = "' . $form['appliances'] . '",
	         features = "' . $form['features'] . '",
	         garage = "' . $form['garage'] . '",
	         garage_cars = "' . $form['garage_cars'] . '",
	         basement = "' . $form['basement'] . '",
	         date_updated = "' . date('Y-m-d') . '",
	         ip_updated = "' . $user_ip . '",
		     type2 = "' . $form['type2'] . '",
		     video = "' . $form['video'] . '",
		     latitude = "' . $form['latitude'] . '",
		     longitude = "' . $form['longitude'] . '",
		     status = "' . $form['status'] . '",
		     approved = "' . $form['approved'] . '",
		     date_approved = '.$approved_date.',
		     calendar = "' . $form['calendar'] . '",
	    	 custom1 = "' . $form['custom1'] . '",
			 custom2 = "' . $form['custom2'] . '",
			 custom3 = "' . $form['custom3'] . '",
			 custom4 = "' . $form['custom4'] . '",
			 custom5 = "' . $form['custom5'] . '",
			 custom6 = "' . $form['custom6'] . '",
			 custom7 = "' . $form['custom7'] . '",
			 custom8 = "' . $form['custom8'] . '",
			 custom9 = "' . $form['custom9'] . '",
			 custom10 = "' . $form['custom10'] . '"
	         WHERE id = "' . intval($_GET['id']) . '"';

        $db->query($sql) or error ('Critical Error', mysql_error ());

        // Update the property types counters for this listings
        update_categories ($f['type'] , $form['type']);

        $sql = 'SELECT * FROM ' . FEATURED_TABLE . ' WHERE id = "' . $_GET['id'] . '" LIMIT 1';
        $r_featured = $db->query ($sql) or error ('Critical Error', mysql_error () );
        $f_featured = $db->fetcharray($r_featured);

        if ($form['package'] != $f_featured['package'])
 	 update_package ( intval($_GET['id']), $form['package'] );

	echo $lang['Listing_Updated'];

       }

      echo table_footer ( );

     }

    echo table_header ( $lang['Video_Upload_File'] );
    // Output the form

    if (isset($video_uploaded) && $video_uploaded == TRUE)
     echo '<center><B>' . $lang['Video_OK'] . '</b></center>';

    if (isset($video_uploaded) && $video_uploaded == FALSE)
     echo '<center><B>' . $lang['Video_BAD'] . '</b></center>';


    // Show image if exist

    if (file_exists(PATH . '/video/' . $f['id'] . '.flv'))
     echo '<p align="center">' . $lang['Video_Upload_File_Exists'] . '</p>';

    echo '
     <form action="' . URL . '/admin/editlistings.php?id=' . intval($_GET['id']) . '" method="POST" enctype="multipart/form-data">
      <table width="100%" cellpadding="5" cellspacing="0" border="0">
         ';

    echo userform ($lang['Video_Upload_File'], '<input type="file" size="40" name="video_file" maxlength="50">', '1');
    echo userform ('', '<input type="Submit" name="submit_video" value="' . $lang['Video_Upload'] . '"><input type="Submit" name="submit_video2" value="' . $lang['Video_Remove'] . '">');

    echo '
      </table>
     </form>
         ';

    echo table_footer();

    // Upload image form

    echo table_header ( $lang['Listing_Image'] );

    // Output the form

    // Show image if exist
    echo '<p align="center">' . show_image ('images', $f['id']) . '</p>';

    echo '
     <form action="' . URL . '/admin/editlistings.php?id=' . intval($_GET['id']) . '" method="POST" enctype="multipart/form-data">
      <table width="100%" cellpadding="5" cellspacing="0" border="0">
         ';

    echo userform ($lang['Listing_Image_File'], '<input type="file" size="40" name="image_file" maxlength="50">', '1');
    echo userform ('', '<input type="Submit" name="submit_image" value="' . $lang['Listing_Submit_Image'] . '"> <input type="Submit" name="submit_image_remove" value="' . $lang['Listing_Submit_Image_Remove'] . '">');

    echo '
      </table>
     </form>
         ';

    // If image was uploaded
    if (isset($uploaded) && $uploaded)
     echo '<p align="center"><span class="warning">' . $lang['Listing_Image_Uploaded'] . '</span></p>';

    // If image was not uploaded because of the image
    // size problems etc.
    if (isset($uploaded) && !$uploaded)
     echo '<p align="center"><span class="warning">' . $lang['Listing_Image_NOT_Uploaded'] . '</p>';

    echo table_footer ();

    // Upload banner form

    echo table_header ( $lang['Listing_Banner'] );

    // Output the form

    // Show image if exist
    echo '<p align="center">' . show_banner ('banners', $f['id']) . '</p>';

    echo '
     <form action="' . URL . '/admin/editlistings.php?id=' . intval($_GET['id']) . '" method="POST" enctype="multipart/form-data">
      <table width="100%" cellpadding="5" cellspacing="0" border="0">
         ';

    echo userform ($lang['Listing_Banner_File'], '<input type="file" size="40" name="image_file" maxlength="50">', '1');
    echo userform ('', '<input type="Submit" name="submit_banner" value="' . $lang['Listing_Submit_Banner'] . '"> <input type="Submit" name="submit_banner_remove" value="' . $lang['Listing_Submit_Banner_Remove'] . '">');

    echo '
      </table>
     </form>
         ';

    // If image was uploaded
    if (isset($uploaded_banner) && $uploaded_banner)
     echo '<p align="center"><span class="warning">' . $lang['Listing_Banner_Uploaded'] . '</span></p>';

    // If image was not uploaded because of the image
    // size problems etc.
    if (isset($uploaded_banner) && !$uploaded_banner)
     echo '<p align="center"><span class="warning">' . $lang['Listing_Banner_NOT_Uploaded'] . '' . $conf['banner_width'] . 'x' . $conf['banner_height'] . ' @ ' . $conf['banner_size'] /1024 . ' Kbytes.</span></p>';

    echo table_footer ();


    // Navigation
    echo table_header ( $lang['Navigation'] );
    // Back to the listings search using the cached search values
    echo '- <a href="' . URL . '/admin/findlistings.php?' . $session->fetch('listingsearchvariables') . '">' . $lang['Search_Back_Listing'] . '</a><br />';

    echo table_footer ();

    //

    // Main form

    echo table_header ( $lang['Menu_Submit_Property'] );

    $sql = 'SELECT * FROM ' . FEATURED_TABLE . ' WHERE id = ' . $f['id'] . ' LIMIT 1';
    $r_featured = $db->query ($sql) or error ('Critical Error', mysql_error () );
    $f_featured = $db->fetcharray($r_featured);

    // Define the form variables if the form was not updated
    if (!isset($form))
     {

      $form = array();

		$form['title'] = $f['title'];
		$form['title2']  = $f['title2'];
		$form['title3']  = $f['title3'];
		$form['title4']  = $f['title4'];
		$form['title5']  = $f['title5'];
		$form['title6']  = $f['title6'];
		$form['title7']  = $f['title7'];
		$form['title8']  = $f['title8'];
		$form['title9']  = $f['title9'];
		$form['title10']  = $f['title10'];
		$form['title11']  = $f['title11'];
		$form['title12']  = $f['title12'];
		$form['title13']  = $f['title13'];
		$form['title14']  = $f['title14'];
		$form['title15']  = $f['title15'];
		$form['title16']  = $f['title16'];
		$form['title17']  = $f['title17'];
		$form['title18']  = $f['title18'];
		$form['title19']  = $f['title19'];
		$form['title20']  = $f['title20'];
		$form['title21']  = $f['title21'];
		$form['title22']  = $f['title22'];
		$form['title23']  = $f['title23'];
		$form['title24']  = $f['title24'];
		$form['title25']  = $f['title25'];
		$form['title26']  = $f['title26'];
		$form['title27']  = $f['title27'];
		$form['title28']  = $f['title28'];
		$form['title29']  = $f['title29'];
		$form['title30']  = $f['title30'];

		$form['description']  = $f['description'];
		$form['description2']  = $f['description2'];
		$form['description3']  = $f['description3'];
		$form['description4']  = $f['description4'];
		$form['description5']  = $f['description5'];
		$form['description6']  = $f['description6'];
		$form['description7']  = $f['description7'];
		$form['description8']  = $f['description8'];
		$form['description9']  = $f['description9'];
		$form['description10']  = $f['description10'];
		$form['description11']  = $f['description11'];
		$form['description12']  = $f['description12'];
		$form['description13']  = $f['description13'];
		$form['description14']  = $f['description14'];
		$form['description15']  = $f['description15'];
		$form['description16']  = $f['description16'];
		$form['description17']  = $f['description17'];
		$form['description18']  = $f['description18'];
		$form['description19']  = $f['description19'];
		$form['description20']  = $f['description20'];
		$form['description21']  = $f['description21'];
		$form['description22']  = $f['description22'];
		$form['description23']  = $f['description23'];
		$form['description24']  = $f['description24'];
		$form['description25']  = $f['description25'];
		$form['description26']  = $f['description26'];
		$form['description27']  = $f['description27'];
		$form['description28']  = $f['description28'];
		$form['description29']  = $f['description29'];
		$form['description30']  = $f['description30'];

      $form['package'] = $f_featured['package'];
      $form['mls'] = $f['mls'];
      $form['type'] = $f['type'];
      $form['style'] = $f['style'];
      $form['size'] = $f['size'];
      $form['dimensions'] = $f['dimensions'];
      $form['bathrooms'] = $f['bathrooms'];
      $form['half_bathrooms'] = $f['half_bathrooms'];
      $form['bedrooms'] = $f['bedrooms'];

      $locations_array = explode("#", $f['location2']);
      $form['location1'] = $locations_array[0];
      $form['location2'] = $locations_array[1];
      $form['location3'] = $locations_array[2];

      $form['zip'] = $f['zip'];
      $form['address1'] = $f['address1'];
      $form['address2'] = $f['address2'];
      $form['display_address'] = $f['display_address'];
      $form['price'] = $f['price'];
      $form['directions'] = $f['directions'];
      $form['year_built'] = $f['year_built'];
      $form['buildings'] = $f['buildings'];
      $form['appliances'] = $f['appliances'];
      $form['features'] = $f['features'];
      $form['garage'] = $f['garage'];
      $form['garage_cars'] = $f['garage_cars'];
      $form['basement'] = $f['basement'];
      $form['type2'] = $f['type2'];
      $form['video'] = $f['video'];
      $form['calendar'] = $f['calendar'];
      $form['latitude'] = $f['latitude'];
      $form['longitude'] = $f['longitude'];
      $form['status'] = $f['status'];
      $form['approved'] = $f['approved'];

      // Custom fields
      $form['custom1'] = str_replace( '{INPUT}', '', $f['custom1'] );
      $form['custom2'] = str_replace( '{INPUT}', '', $f['custom2'] );
      $form['custom3'] = str_replace( '{INPUT}', '', $f['custom3'] );
      $form['custom4'] = str_replace( '{INPUT}', '', $f['custom4'] );
      $form['custom5'] = str_replace( '{INPUT}', '', $f['custom5'] );
      $form['custom6'] = str_replace( '{INPUT}', '', $f['custom6'] );
      $form['custom7'] = str_replace( '{INPUT}', '', $f['custom7'] );
      $form['custom8'] = str_replace( '{INPUT}', '', $f['custom8'] );
      $form['custom9'] = str_replace( '{INPUT}', '', $f['custom9'] );
      $form['custom10'] = str_replace( '{INPUT}', '', $f['custom10'] );
      
     }
     else
     {
      // Custom fields
      $form['custom1'] = str_replace( '{INPUT}', '', $form['custom1'] );
      $form['custom2'] = str_replace( '{INPUT}', '', $form['custom2'] );
      $form['custom3'] = str_replace( '{INPUT}', '', $form['custom3'] );
      $form['custom4'] = str_replace( '{INPUT}', '', $form['custom4'] );
      $form['custom5'] = str_replace( '{INPUT}', '', $form['custom5'] );
      $form['custom6'] = str_replace( '{INPUT}', '', $form['custom6'] );
      $form['custom7'] = str_replace( '{INPUT}', '', $form['custom7'] );
      $form['custom8'] = str_replace( '{INPUT}', '', $form['custom8'] );
      $form['custom9'] = str_replace( '{INPUT}', '', $form['custom9'] );
      $form['custom10'] = str_replace( '{INPUT}', '', $form['custom10'] );
     }

 	  // Default for approval
 	  if ($form['approved'] == '' || $form['approved'] == '0')
 	  	$approved0 = 'selected';
 	  elseif ($form['approved'] == '1')
 	  	$approved1 = 'selected';
 	  else
 	  	$approved2 = 'selected';

    // Output the form
    echo '
     <form action="' . URL . '/admin/editlistings.php?id=' . intval($_GET['id']) . '" method="POST" name="form">
      <table width="100%" cellpadding="5" cellspacing="0" border="0">
         ';

    echo userform ('ID', $f['id']);

    echo userform ($lang['Listing_Approval'], '<select name="approved" class="formEditSelect"><option value="1" ' . $approved1 . '>Active</option><option value="0" ' . $approved0 . '>Inactive</option><option value="2" ' . $approved2 . '>Expired</option></select>');
    echo userform ($lang['Admin_Packages_Name'], '<select name="package"><option value="0">Free</option>' . generate_packages_list($form['package']) . '</select>');

    if ($form['package'] != 0)
     echo userform ($lang['Admin_Listing_Expire'], printdate($f_featured['end_date']));

    echo userform ($lang['Module_Listing_Type'], '<select name="type2">' . generate_options_list(TYPES2_TABLE, $form['type2']) . '</select>', '1');
    echo userform ($lang['Listing_Status'], '<select name="status" class="formEditSelect">' . generate_options_list(STATUS_TABLE, $form['status']) . '</select>', '1');
    if (strcasecmp(@$conf['show_mls'], 'OFF') != 0) {
        echo userform ($lang['Listing_MLS'], '<input type="text" size="45" name="mls" value="' . $form['mls'] . '" maxlength="10">');
    }

	// Show all available languages
	foreach ($installed_languages AS $language1 => $key1)
	{
		$key1 = str_replace( 'name', 'title', $key1 );
		$title_html .= '<a href="javascript:void(0);" onclick="jQuery(\'#' . $key1 . '\').show();">' . ucwords($language1) . '</a>&nbsp;&nbsp;';
	}

	// Display text boxes for every language
	$num = 1;
	foreach ($installed_languages AS $language1 => $key1)
	{
		// Grab the right text for each textarea
		$strip = str_replace( 'name', 'title', $key1 );
		$key1 = str_replace( 'name', 'title', $key1 );

		if ($num == 1)
			$display = 'normal';
		else
			$display = 'none';

		$title_html .= '
		<div style="display: ' . $display . ';" id="' . $key1 . '">
		<input type="text" size="100" maxlength="255" name="' . $key1 . '" id="' . $key1 . '" class="formSubmitInput" value="' . $form[$strip] . '">
		<br /><a href="javascript:void(0);" onclick="jQuery(\'#' . $key1 . '\').hide();">Hide ' . ucwords($language1) . '</a>
		</div>
		';

		$num++;
	}

    echo userform ($lang['Listing_Title'], $title_html, '1');

    echo userform ($lang['Listing_Property_Type'], '<select name="type">' . generate_options_list(TYPES_TABLE, $form['type']) . '</select>', '1');
    echo userform ($lang['Listing_Style'], '<select name="style">' . generate_options_list(STYLES_TABLE, $form['style']) . '</select>', '1');

	// Show all available languages
	foreach ($installed_languages AS $language1 => $key1)
	{
		// Grab the right text for each textarea
		$key1 = str_replace( 'name', 'description', $key1 );
		$description_html .= '<a href="javascript:void(0);" onclick="jQuery(\'#' . $key1 . '\').show();">' . ucwords($language1) . '</a>&nbsp;&nbsp;';
	}

	// Display text boxes for every language
	$num = 1;
	foreach ($installed_languages AS $language1 => $key1)
	{
		// Grab the right text for each textarea
		$strip = str_replace( 'name', 'description', $key1 );
		$key1 = str_replace( 'name', 'description', $key1 );

		if ($num == 1)
			$display = 'normal';
		else
			$display = 'none';

		$description_html .= '
		<div style="display: ' . $display . ';" id="' . $key1 . '">
		<textarea class="ckeditor" cols="100" rows="20" class="formSubmitArea" name="' . $key1 . '" id="' . $key1 . '">' . unsafehtml($form[$strip]) . '</textarea>
		<br /><a href="javascript:void(0);" onclick="jQuery(\'#' . $key1 . '\').hide();">Hide ' . ucwords($language1) . '</a>
		</div>
		';

		$num++;
	}

   echo userform ($lang['Listing_Description'], $description_html, '1');

    echo userform ($lang['Listing_Lot_Size'], '<input type="text" size="45" name="size" value="' . $form['size'] . '" maxlength="50">');
    echo userform ($lang['Listing_Dimensions'], '<input type="text" size="45" name="dimensions" value="' . $form['dimensions'] . '" maxlength="50">');
    echo userform ($lang['Listing_Bathrooms'], '<input type="text" size="45" name="bathrooms" value="' . $form['bathrooms'] . '" maxlength="2">');
    echo userform ($lang['Listing_Half_Bathrooms'], '<input type="text" size="45" name="half_bathrooms" value="' . $form['half_bathrooms'] . '" maxlength="2">');
    echo userform ($lang['Listing_Bedrooms'], '<input type="text" size="45" name="bedrooms" value="' . $form['bedrooms'] . '" maxlength="2">');

// ==

  $r_location1 = $db->query('SELECT selector, category FROM ' . LOCATION1_TABLE . ' ORDER by category');

  $newContentMain = '';
  $newContentMain2 = '';
  $newContentMain3 = '';

  while ($f_location1 = $db->fetcharray($r_location1)) {
   if ($f_location1['selector'] == $form['location1']) $selected = 'SELECTED'; else $selected = '';
   $newContentMain.= '<option value="' . $f_location1['selector'] . '" ' . $selected . '>' . $f_location1['category'] . '</option>' . "/n";
  }

  if ($form['location2'] != '0') {
   // Fetch the second level locations data
   $r_location2 = $db->query('SELECT catsubsel, subcategory FROM ' . LOCATION2_TABLE . ' WHERE catsel = "' . $form['location1'] . '" ORDER BY subcategory ASC');

   $newContentMain2.= '<br /><select name="location2" class="span3" id="location2" onchange="xajax_fetchLocations3(this.value);">';

   while ($f_location2 = $db->fetcharray($r_location2)) {
    if ($f_location2['catsubsel'] == $form['location2']) $selected = 'SELECTED'; else $selected = '';
    $newContentMain2.= '<option value="' . $f_location2['catsubsel'] . '" ' . $selected . '>' . $f_location2['subcategory'] . '</option>';
   }

   $newContentMain2.= '</select>';
  }

  if ($form['location3'] != '0') {
   // Fetch the third level locations data
   $r_location3 = $db->query('SELECT catsubsubsel, subsubcategory FROM ' . LOCATION3_TABLE . ' WHERE catsubsel = "' . $form['location2']. '" ORDER BY subsubcategory ASC');

   $newContentMain3.= '<br /><select name="location3" class="span3" id="location3">';

   while ($f_location3 = $db->fetcharray($r_location3)) {
    if ($f_location3['catsubsubsel'] == $form['location3']) $selected = 'SELECTED'; else $selected = '';
    $newContentMain3.= '<option value="' . $f_location3['catsubsubsel'] . '" ' . $selected . '>' . $f_location3['subsubcategory'] . '</option>';
   }

   $newContentMain3.= '</select>';
  }

  echo userform ($lang['Location'], '
          <select name="location1" class="span3" id="location1" onchange="xajax_fetchLocations2(this.value);">' . $newContentMain . '</select>
          <div style="display: inline" id="location2div" name="location2div">' . $newContentMain2 . '</div>
          <div style="display: inline" id="location3div" name="location3div">' . $newContentMain3 . '</div>', '1');

// ==

    if (strcasecmp(@$conf['show_postal_code'], 'OFF') != 0) {
        echo userform ($lang['Zip_Code'], '<input type="text" size="45" name="zip" value="' . $form['zip'] . '" maxlength="20">');
    }
    echo userform ($lang['Listing_Address1'], '<input type="text" size="45" name="address1" value="' . $form['address1'] . '" maxlength="50">');
    echo userform ($lang['Listing_Address2'], '<input type="text" size="45" name="address2" value="' . $form['address2'] . '" maxlength="50">');

    if ($form['display_address'] == 'YES') $display_address_checked = 'CHECKED'; else $display_address_checked = '';

    echo userform ($lang['Listing_Latitude'], '<input type="text" name="latitude" value="' . $form['latitude'] . '" maxlength="50" class="formSubmitInput">');
    echo userform ($lang['Listing_Longitude'], '<input type="text" name="longitude" value="' . $form['longitude'] . '" maxlength="50" class="formSubmitInput">');

    echo userform ($lang['Listing_Display_Address'], '<input type="checkbox" name="display_address" value="YES" ' . $display_address_checked . '>');
    echo userform ($lang['Listing_Price'], '<input type="text" size="45" name="price" value="' . $form['price'] . '" maxlength="13">');
    echo userform ($lang['Listing_Directions'], '<textarea class="ckeditor" wrap="soft" cols="45" rows="4"  name="directions" onKeyDown="textCounter(this.form.directions,this.form.listing_directions_counter, ' . $conf['listing_directions_size'] . ');" onKeyUp="textCounter(this.form.directions,this.form.listing_directions_counter, ' . $conf['listing_directions_size'] . ');">' . unsafehtml($form['directions']) . '</textarea>');
    echo userform ('', '<input readonly type="text" name="listing_directions_counter" size="5" maxlength="5" value="' . $conf['listing_directions_size'] . '"> ' . $lang['Characters_Left']);
    echo userform ($lang['Listing_Year_Built'], '<input type="text" size="45" name="year_built" value="' . $form['year_built'] . '" maxlength="4">');

    if (!isset($form['buildings'])) $form['buildings'] = '';
    if (!isset($form['appliances'])) $form['appliances'] = '';
    if (!isset($form['features'])) $form['features'] = '';

    echo userform ($lang['Listing_Additional_Out_Buildings'], generate_checkbox_list(BUILDINGS_TABLE, 'buildings', explode(':', $form['buildings'])));
    echo userform ($lang['Listing_Appliances_Included'], generate_checkbox_list(APPLIANCES_TABLE, 'appliances', explode(':', $form['appliances'])));
    echo userform ($lang['Listing_Features'], generate_checkbox_list(FEATURES_TABLE, 'features', explode(':', $form['features'])));
    echo userform ($lang['Listing_Garage'], '<select name="garage">' . generate_options_list(GARAGE_TABLE, $form['garage']) . '</select>');
    echo userform ($lang['Listing_Garage_Cars'], '<input type="text" size="45" name="garage_cars" value="' . $form['garage_cars'] . '" maxlength="2">');
    echo userform ($lang['Listing_Basement'], '<select name="basement">' . generate_options_list(BASEMENT_TABLE, $form['basement']) . '</select>');
    echo userform ($lang['Video_Tour'], '<input type="text" size="45" name="video" value="' . $form['video'] . '" maxlength="255">');
    
	// Custom fields
	$query = "SELECT * FROM " . FIELDS_TABLE . " ORDER BY name ASC";
	$result = $db->query($query) OR error($query);
	if ($db->numrows($result) > 0) {
		while($row = $db->fetcharray($result)) {
			// Type of input
			if ($row['type'] != '') {
				if ($row['type'] == 'input') {
					echo userform ($row['name'], '<input type="text" name="' . $row['field'] . '" value="' . $form[$row['field']] . '" class="formSubmitInput">');
				} elseif ($row['type'] == 'select') {
					// Grab all options for this select
					$options = "SELECT * FROM " . VALUES_TABLE . " WHERE f_id = '" . addslashes($row['id']) . "'";
					$get_options = $db->query($options) OR error($options);
					if ($db->numrows($get_options) > 0) {
						while($row2 = $db->fetcharray($get_options)) {
							if ($row2['id'] == $form[$row['field']]) {
								$selected = ' selected';
							} else {
								$selected = '';
							}
							$option_list .= "<option value=\"" . $row2['id'] . "\" " . $selected . ">" . $row2['name'] . "</option>";
						}
						echo userform ($row['name'], '<select name="' . $row['field'] . '" class="formSubmitSelect"><option value="">Please Select</option>' . $option_list . '</select>');
					}
				}
			}
		}
	}
	// Show calendar if enabled
	if ($conf['show_calendar'] == 'ON')
	{
        echo '<tr id="calendarBox"><td colspan="2" align="center">

    <p><b><u>' . $lang['Availability_Calendar'] . '</u></b></p>';

        $dates = explode(',', $form['calendar']);
        foreach ($dates as $k => $date) {
            if (strlen(trim($date)) == 0) {
                unset($dates[$k]);
                continue;
            }
            list($month, $day, $year) = explode('/', $date);
            if (date('Y-m-d') > $year.'-'.$month.'-'.$day) {
                unset($dates[$k]);
            }
        }
        $form['calendar'] = implode(',', $dates);
        if ($form['calendar']) {
            $form['calendar'] .= ',';
        }

        echo '
    <textarea name="calendar" id="calendar_output" style="display:none;">' . unsafehtml($form['calendar']) . '</textarea>
    <input type="hidden" name="dateTemp" id="dateTemp" value="" />
    <div id="calendar-container"></div>

    <script type="text/javascript">
    function dateAvailable(y, m, d) {
        m = (++m < 10) ? "0" + m : m;
        d = (d < 10) ? "0" + d : d;
        return document.getElementById("calendar_output").value.indexOf("" + m + "/" + d + "/" + y + ",");
    }

    function toggleDateAvailable(cal) {
        var storage = document.getElementById("calendar_output");
        var d = document.getElementById("dateTemp").value + ",";
        var dateParts = document.getElementById("dateTemp").value.split("/");
        var date = new Date(dateParts[2], dateParts[0] - 1, dateParts[1]);
        var list = storage.value;
        var pos = list.indexOf(d);
        if (pos >= 0) {
            if (list.length == 11) {
                storage.value = "";
            } else if (pos == 0) {
                storage.value = list.substring(pos + 11);
            } else {
                storage.value = list.substring(0, pos) + list.substring(pos + 11);
            }
       } else {
            storage.value += d;
       }
       cal._init(cal.firstDayOfWeek, date);
    }

    var today = new Date();
    today.setHours(0, 0, 0 ,0);
    Calendar.setup(
      {
        flat         : "calendar-container", // ID of the parent element
        dateStatusFunc : function(date, y, m, d) {
                           if (date < today) {
                            return true;
                           } else if (dateAvailable(y, m, d) >= 0) {
                            return "special";
                           }
                           return false;
                         },
          inputField  : "dateTemp",
          ifFormat    : "%m/%d/%Y",
          weekNumbers : false,
          onUpdate    : function (cal) {
            if (cal.dateClicked) {
                toggleDateAvailable(cal);
            }
          },
          range : new Array('.date('Y').', '.(date('Y') + 1).')
       }
    );
    </script>
    ';

        echo '
    <script type="text/javasscript">
    (function($){
        $(document).ready(function () {
            $("#calendarBox").show();
        });
    })(jQuery);
    </script>
    <div id="calendar-legend">
        <p class="calendarAvailable"><span>'.$lang['Availability_Calendar_Vacancy'].'</span></p>
        <p class="calendarUnavailable"><span>'.$lang['Availability_Calendar_No_Vacancy'].'</span></p>
    </div>

    </td></tr>';
    }

    echo userform ('', '<input type="Submit" name="submit_listing" value="' . $lang['Listing_Submit'] . '">');

    echo '
      </table>
     </form>
         ';

    echo table_footer ();

    // Statistics

    echo table_header ( $lang['Information'] );

    echo '<span class="bold">' . $lang['Listing_Added_Date'] . ':</span> ' . printdate($f['date_added']) . ' (' . $f['ip_added'] . ', ' . @gethostbyaddr($f['ip_added']) . ') <br />';

    if (!empty($f['date_updated']))
     echo '<span class="bold">' . $lang['Listing_Updated_Date'] . ':</span> ' . printdate($f['date_updated']) . ' (' . $f['ip_updated'] . ', ' . @gethostbyaddr($f['ip_updated']) . ') <br />';

    echo '<span class="bold">' . $lang['Hits'] . ':</span> ' . $f['hits'] . ' <br />';

    echo table_footer ();

   }

  else

   echo 'Listing ID not specified';

 }

else

 error ('Critical Error' , 'Please, login to access this script.');

// Template footer
include ( PATH . '/admin/template/footer.php' );

?>